package net.huashitong.shiro;

import net.huashitong.config.ProjectConfig;
import net.huashitong.entity.UserMessage;
import net.huashitong.service.user.UserService;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.user.entity.vo.LoginOutVO;
import net.huashitong.ssydt.user.entity.vo.UserOutVO;
import net.huashitong.user.results.UserPlain;
import net.huashitong.user.vo.ThirdLoginVO;
import net.huashitong.user.vo.UserLoginVO;
import net.huashitong.util.PasswordHelper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

;

/**
 * 系统安全认证实现类
 *
 * @author ThinkGem
 * @version 2013-5-29
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(SystemAuthorizingRealm.class);

    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private UserService userService;

    private HttpServletRequest request;

    String salt = "f823bbde9c7c5cd816664e1b323ee6eb";

    /**
     * 认证回调函数, 登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        SimpleAuthenticationInfo authenticationInfo = null;

        String loginMode = token.getLoginMode();
        if (loginMode.equals("WeChat")) {//微信登录
            authenticationInfo = updateWeChatLogin(token);
        } else {//用户名密码登录
            authenticationInfo = updateUsernameLogin(token);
        }
//        UserPlain userPlain = (UserPlain) authenticationInfo.getPrincipals().getPrimaryPrincipal();
//        String userId = userPlain.getUserId();
        //登录后如果账户为空，生成账户
//        userService.updateAccountAndRegister(userId,ProjectConfig.PRODUCT_CODE);


        return authenticationInfo;
    }


    /**
     * 微信登录
     *
     * @param token
     * @return
     */
    private SimpleAuthenticationInfo updateWeChatLogin(UsernamePasswordToken token) {
        ThirdLoginVO thirdLoginVO = getThirdLoginVO(token, "WeChat");
        UserPlain userPlain;
        try {
            userPlain = userService.thirdLogin(thirdLoginVO);
        } catch (Exception e) {
            throw new IncorrectCredentialsException();
        }
        UserOutVO userOutVO = userService.getByUserId(userPlain.getUserId());
        //验证用户信息
        return new SimpleAuthenticationInfo(
                new UserMessage(userOutVO),//用户信息，需要多少信息就为对象赋多少属性
                "123456",
                getName());
    }

    /**
     * 用户名密码登录
     *
     * @param token
     * @return
     */
    private SimpleAuthenticationInfo updateUsernameLogin(UsernamePasswordToken token) {
        //用户名密码登录
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setIp(token.getHost());
        userLoginVO.setUserAgent("");
        userLoginVO.setPassword(String.valueOf(token.getPassword()));
        userLoginVO.setMobile(token.getUsername());
        userLoginVO.setTerminal("Browser");
        userLoginVO.setProductSource(ProjectConfig.PRODUCT_CODE);
        LoginOutVO loginOutVO;
        try {
            loginOutVO = userService.login(userLoginVO);
        } catch (Exception ue) {
            throw new ServiceException("账号或密码错误");
        }
        UserOutVO userOutVO = userService.getByUserId(loginOutVO.getUserId());
//        token.setPassword("123456".toCharArray());
        //验证用户信息
        return new SimpleAuthenticationInfo(
                new UserMessage(userOutVO),//用户信息，需要多少信息就为对象赋多少属性
                token.getPassword(),
                getName());
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        //获取用户信息
//        SysPrincipal principal = SysUserUtils.getSysPrincipal();
//        String roleId = principal.getRoleId();
//        String deptId = principal.getDeptId();
//
//        //赋予权限信息
//        List<String> permissions = sysRolePermissionService.queryPermissionByRoleIdDeptId(roleId, deptId);
//        SysLogin user = sysLoginService.getById(principal.getUserId());
//        if (user != null && CollectionsUtils.isNotEmpty(permissions)) {
//            SimpleAuthorizationInfo info = constructInfo(permissions);//添加权限字符信息
//            info.addRole(roleId.toString());//添加角色
//            return info;
//        }
        return null;
    }


    private ThirdLoginVO getThirdLoginVO(UsernamePasswordToken token, String type) {
        ThirdLoginVO vo = new ThirdLoginVO();
        vo.setIp(token.getRequest().getRemoteAddr());
        vo.setUserAgent(token.getRequest().getHeader("User-Agent"));
        vo.setThirdAccount(type);
        vo.setToken(token.getUsername());
        vo.setTerminal("Browser");
        vo.setProductSource(ProjectConfig.PRODUCT_CODE);
        vo.setMobile(token.getMobile());
        return vo;
    }
}